package com.yinshan.printer.service;

import android.os.Handler;

import com.newland.me.ConnUtils;
import com.newland.me.DeviceManager;
import com.newland.mtype.ConnectionCloseEvent;
import com.newland.mtype.ModuleType;
import com.newland.mtype.event.DeviceEventListener;
import com.newland.mtype.module.common.printer.PrintContext;
import com.newland.mtype.module.common.printer.Printer;
import com.newland.mtype.module.common.printer.PrinterResult;
import com.newland.mtype.module.common.printer.PrinterStatus;
import com.newland.mtypex.nseries3.NS3ConnParams;
import com.yinshan.printer.bean.PrintData;
import com.yinshan.printer.utils.Logs;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

public class N9PrintService extends BaseIntentService {
    private static final String K21_DRIVER_NAME = "com.newland.me.K21Driver";
    private DeviceManager deviceManager;
    private Printer printer;

    private StringBuffer mBuffer = new StringBuffer();

    @Override
    void initPrint() {
        deviceManager = ConnUtils.getDeviceManager();
        deviceManager.init(this, K21_DRIVER_NAME, new NS3ConnParams(), new DeviceEventListener<ConnectionCloseEvent>() {
            @Override
            public void onEvent(ConnectionCloseEvent connectionCloseEvent, Handler handler) {
                Logs.d(TAG, "event=" + connectionCloseEvent.toString());
            }

            @Override
            public Handler getUIHandler() {
                return null;
            }
        });
        try {
            deviceManager.connect();
            deviceManager.getDevice().setBundle(new NS3ConnParams());
            printer = (Printer) deviceManager.getDevice().getStandardModule(ModuleType.COMMON_PRINTER);
            printer.init();
        } catch (Exception e) {
            Logs.e(TAG, "e:" + e.getMessage());
            showToast("打印机初始化失败");
        }
    }

    @Override
    void print(ArrayList<PrintData> printDatas) {
        if (null == printer) {
            Logs.d(TAG, "print is null!!!");
            return;
        }
        if (printer.getStatus() != PrinterStatus.NORMAL) {
            if (printer.getStatus() == PrinterStatus.OUTOF_PAPER) {
                showToast("打印机缺纸");
            }
            return;
        }
        Logs.d(TAG, "开始打印");
        for (PrintData item : printDatas) {
            Logs.i(TAG, "print:" + item.toString());
            int space = 3;
            if (item.getTextSize() == PrintData.Font.BIG) {
                space = 5;
            } else if (item.getTextSize() == PrintData.Font.NORMAL) {
                space = 8;
            }
            setTextSize(item.getTextSize(), space);
            setPrintText(item.getText(), item.getTextAlign());
        }
        feedLine(4);
        try {
            Logs.d(TAG, "打印体：" + mBuffer.toString());
            PrinterResult result = printer.printByScript(PrintContext.defaultContext(), mBuffer.toString().getBytes("GBK"), 60, TimeUnit.SECONDS);
            if (result == PrinterResult.OUTOF_PAPER) {
                showToast("打印机缺纸");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            Logs.e(TAG, "e:" + e.getMessage());
        }
    }

    /**
     * 设置字体大小 行数
     *
     * @param font      字体大小
     * @param lineSpace 间隔
     */
    private void setTextSize(PrintData.Font font, int lineSpace) {
        if (font == PrintData.Font.SMALL) {
            mBuffer.append("!hz s\n !asc s\n !gray 5\n");
        } else if (font == PrintData.Font.BIG) {
            mBuffer.append("!hz l\n !asc n\n !gray 5\n");
        } else {
            mBuffer.append("!hz n\n !asc n\n !gray 5\n");
        }
        mBuffer.append("!yspace ").append(lineSpace).append("\n");
    }

    public void setPrintText(String text, PrintData.Align align) {
        if (align == PrintData.Align.CENTER) {
            mBuffer.append("*text c ").append(text).append("\n");
        } else if (align == PrintData.Align.RIGHT) {
            mBuffer.append("*text r ").append(text).append("\n");
        } else {
            mBuffer.append("*text l ").append(text).append("\n");
        }
    }

    /**
     * 走纸行数
     *
     * @param line 走纸数
     */
    public void feedLine(int line) {
        mBuffer.append("*feedline ").append(line).append("\n");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != printer) {
            printer = null;
        }

        if (null != deviceManager) {
            deviceManager.disconnect();
            deviceManager.destroy();
        }
    }
}
